#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "seqlist.h"

// 初始化顺序表
void InitSeqList(SeqList* list) {
    list->capacity = 5;
    list->data = (Book*)malloc(list->capacity * sizeof(Book));
    if (list->data == NULL) {
        printf("内存分配失败！程序退出\n");
        exit(1);
    }
    list->size = 0;
}

// 扩容顺序表（翻倍）
void ExpandSeqList(SeqList* list) {
    int newCapacity = list->capacity * 2;
    Book* newData = (Book*)realloc(list->data, newCapacity * sizeof(Book));
    if (newData == NULL) {
        printf("内存扩容失败！程序退出\n");
        exit(1);
    }
    list->data = newData;
    list->capacity = newCapacity;
    printf("顺序表已扩容到 %d\n", newCapacity);
}

// 按ID查找索引
int FindBookIndex(SeqList* list, const char* id) {
    for (int i = 0; i < list->size; i++) {
        if (strcmp(list->data[i].id, id) == 0) {
            return i;
        }
    }
    return -1;
}

// 末尾插入
void PushBackBook(SeqList* list, Book book) {
    if (list->size >= list->capacity) {
        ExpandSeqList(list);
    }
    list->data[list->size] = book;
    list->size++;
}

// 删除指定索引元素
void RemoveBookByIndex(SeqList* list, int index) {
    if (index < 0 || index >= list->size) return;

    for (int i = index; i < list->size - 1; i++) {
        list->data[i] = list->data[i + 1];
    }
    list->size--;
}

// 释放顺序表
void FreeSeqList(SeqList* list) {
    free(list->data);
    list->data = NULL;
    list->size = 0;
    list->capacity = 0;
}